package online.yysh.charging;

import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatDialog;

import com.google.gson.Gson;

import online.yysh.charging.base.BaseActivity;
import online.yysh.charging.bean.StopChargingBean;
import online.yysh.charging.bean.User;
import online.yysh.charging.bean.request.StopChargingRequest;
import online.yysh.charging.bean.response.GetAuthMsgResponse;
import online.yysh.charging.bean.response.StopChargingResponse;
import online.yysh.charging.utils.HttpUtil;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class ChargingActivity extends BaseActivity {

    private TextView tv_voltage, tv_current, tv_quantity, tv_money, tv_progress;

    //预充电时间
    private int preChargingTime = 120;
    //请求充电状态时间间隔
    private static final int REQUEST_INTERVAL = 1000 * 30;

    //开始充电
    private static final int START_CHARGING = 100;
    //正在充电
    private static final int CHARGING = 200;
    //停止充电
    private static final int STOP_CHARGING = 201;
    //预充电
    private static final int PRE_CHARGING = 202;
    //开始预充电
    private static final int START_PRE_CHARGING = 203;
    //请求充电状态
    private static final int REQUEST_CHARGING_STATUS = 300;
    //停止充电成功
    private static final int STOP_CHARGING_SUCCEED = 400;
    //停止充电失败
    private static final int STOP_CHARGING_FAILED = 401;

    private ImageView iv_charging;
    private AnimationDrawable animationDrawable;
    private TextView tv_cancel, tv_title, tv_time, tv_status;

    //开始充电的时间
    private String startTime;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case START_CHARGING:
                    if (handler.hasMessages(PRE_CHARGING)) {
                        handler.removeMessages(PRE_CHARGING);
                    }
                    tv_status.setText(R.string.charging);
                    User user = (User) msg.obj;
//                    startTime = user.getStartTime();
                    setUserText(user);
                    //显示充电的时间
//                    if (!handler.hasMessages(CHARGING)) {
//                        handler.sendEmptyMessage(CHARGING);
//                    }
                    if (!handler.hasMessages(REQUEST_CHARGING_STATUS)) {
                        handler.sendEmptyMessage(REQUEST_CHARGING_STATUS);
                    }
                    break;
                case CHARGING:
//                    setTime(startTime);
                    handler.sendEmptyMessageDelayed(CHARGING, 1000);
                    break;
                case STOP_CHARGING:
                    stopAnimation();
                    if (handler.hasMessages(PRE_CHARGING)) {
                        handler.removeMessages(PRE_CHARGING);
                    }
                    if (handler.hasMessages(CHARGING)) {
                        handler.removeMessages(CHARGING);
                    }
                    tv_status.setText(R.string.stop_charging);
                    break;
                case PRE_CHARGING:
                    preChargingTime--;
                    if (preChargingTime == 0) {
                        //预充电结束
                        stopAnimation();
                    } else {
                        tv_time.setText(preChargingTime + " S");
                        handler.sendEmptyMessageDelayed(PRE_CHARGING, 1000);
                    }
                    break;
                case START_PRE_CHARGING:

                    tv_time.setText(preChargingTime + " S");
                    tv_status.setText(R.string.pre_charging);
                    handler.sendEmptyMessageDelayed(PRE_CHARGING, 1000);
                    break;
                case REQUEST_CHARGING_STATUS:
                    getChargingStatus();
                    handler.sendEmptyMessageDelayed(REQUEST_CHARGING_STATUS, REQUEST_INTERVAL);
                    break;
                case STOP_CHARGING_SUCCEED:
                    StopChargingBean bean = (StopChargingBean) msg.obj;
                    showStopChargingDialog(bean);
                    handler.sendEmptyMessage(STOP_CHARGING);
                    break;
                case STOP_CHARGING_FAILED:
                    showToast("停止充电失败");
                    break;
            }
        }
    };

    /**
     * 获取充电状态
     */
    private void getChargingStatus() {
        HttpUtil.getInstance().getAuthMsg(openid, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                logE("getAuthMsg:" + result);
                GetAuthMsgResponse getAuthMsgResponse = new Gson().fromJson(result, GetAuthMsgResponse.class);
                if ("ok".equals(getAuthMsgResponse.getStatus())) {
                    User user = getAuthMsgResponse.getData();
                    int status = user.getStatus();
                    if (status == 3) {
                        //正常充电中
                        Message message = Message.obtain();
                        message.what = START_CHARGING;
                        message.obj = user;
                        handler.sendMessage(message);
                    }
                }
            }
        });
    }

    /**
     * 停止充电弹窗
     */
    private void showStopChargingDialog(StopChargingBean stopChargingBean) {
        final AppCompatDialog appCompatDialog = new AppCompatDialog(this);
        View view = getLayoutInflater().inflate(R.layout.dialog_stop_recharge, null);
        TextView tv_detail = view.findViewById(R.id.tv_detail);
        String detail = "充电金额：" + stopChargingBean.getUse_money() + "元\n充电电量：" + stopChargingBean.getUseKWh() + "度";
        tv_detail.setText(detail);
        TextView tv_cancel = view.findViewById(R.id.tv_cancel);
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                appCompatDialog.dismiss();
                finish();
            }
        });
        TextView tv_confirm = view.findViewById(R.id.tv_confirm);
        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                appCompatDialog.dismiss();
                finish();
            }
        });
        appCompatDialog.setContentView(view);
        Window window = appCompatDialog.getWindow();
        window.setBackgroundDrawableResource(R.color.transparent);
        window.setGravity(Gravity.CENTER);
        window.setLayout(700, ViewGroup.LayoutParams.WRAP_CONTENT);
        appCompatDialog.show();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_charging;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        iv_charging = findViewById(R.id.iv_charging);
        tv_cancel = findViewById(R.id.tv_cancel);
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        tv_status = findViewById(R.id.tv_status);
        tv_title = findViewById(R.id.tv_title);
        tv_title.setText(R.string.charging_status);
        tv_time = findViewById(R.id.tv_time);
        tv_current = findViewById(R.id.tv_current);
        tv_money = findViewById(R.id.tv_money);
        tv_progress = findViewById(R.id.tv_progress);
        tv_voltage = findViewById(R.id.tv_voltage);
        tv_quantity = findViewById(R.id.tv_quantity);
    }

    /**
     * 开始动画
     */
    private void startAnimation() {
        if (!animationDrawable.isRunning()) {
            animationDrawable.start();
        }
    }

    /**
     * 结束动画
     */
    private void stopAnimation() {
        if (animationDrawable.isRunning()) {
            animationDrawable.stop();
        }
    }

    @Override
    protected void initData() {
        animationDrawable = (AnimationDrawable) iv_charging.getBackground();
        startAnimation();
        //判断是否是正在充电中
        boolean isNewCharging = getIntent().getBooleanExtra("isNewCharging", false);
        if (isNewCharging) {
            //开始充电后有120s的预充电时间，这段时间用来判断枪与车子连接是否正常等一系列准备工作
            handler.sendEmptyMessage(START_PRE_CHARGING);
            handler.sendEmptyMessage(REQUEST_CHARGING_STATUS);
        } else {
            //说明是在充电状态中退出的该页面
            User user = (User) getIntent().getSerializableExtra("User");
            setUserText(user);
            startTime = user.getStartTime();
            getChargingStatus();
        }
    }

    /**
     * 填充数据
     *
     * @param user
     */
    private void setUserText(User user) {
        tv_money.setText(user.getUserMoney() + "");
        tv_current.setText(user.getCur());
        tv_progress.setText(user.getSOC() + "%");
        tv_voltage.setText(user.getVoltage());
        tv_quantity.setText(user.getUseKWh() + "");
//        setTime(user.getStartTime());

        tv_time.setText("充电进度:" + user.getSOC() + "%");
    }

    private void setTime(String startTime) {
        long chargingTime = getChargingTime(startTime) / 1000;
        long hLong = chargingTime / (60 * 60);
        long mLong = chargingTime / 60;
        long sLong = chargingTime % 60;
        String h = String.valueOf(hLong);
        if (h.length() < 2) {
            h = "0" + h;
        }
        String m = String.valueOf(mLong);
        if (m.length() < 2) {
            m = "0" + m;
        }
        String s = String.valueOf(sLong);
        if (s.length() < 2) {
            s = "0" + s;
        }
        tv_time.setText(h + ":" + m + ":" + s);
    }

    private long lastClickTime = 0;

    /**
     * 停止充电
     *
     * @param view
     */
    public void stopCharging(View view) {
        if (System.currentTimeMillis() - lastClickTime < 5000) {
            lastClickTime = System.currentTimeMillis();
            return;
        }
        lastClickTime = System.currentTimeMillis();
        StopChargingRequest request = new StopChargingRequest(openid, 1, "");
        HttpUtil.getInstance().stopCharge(request, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                logE("stopCharge:" + result);
                StopChargingResponse stopChargingResponse = new Gson().fromJson(result, StopChargingResponse.class);
                if ("ok".equals(stopChargingResponse.getStatus())) {
                    StopChargingBean data = stopChargingResponse.getData();
                    Message message = Message.obtain();
                    message.what = STOP_CHARGING_SUCCEED;
                    message.obj = data;
                    handler.sendMessage(message);
                } else {
                    handler.sendEmptyMessage(STOP_CHARGING_FAILED);
                }
            }
        });
    }

    /**
     * 获取已经充电的时间
     *
     * @param startTime
     * @return
     */
    private long getChargingTime(String startTime) {
        //2020/11/26 16:28:19
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        long start = 0;
        try {
            start = sdf.parse(startTime).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long now = System.currentTimeMillis();
        return now - start;
    }

}
